<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class AppCreateForm extends CFormModel
{
    public $osrConsumerKey;
    public $osrConsumerSecret;
    public $osrRequesterName;
    public $osrApplicationDescr;

    public function init(){
        $this->osrConsumerKey    = CUtils::generateKey(true);
        $this->osrConsumerSecret = CUtils::generateKey();
    }
    public function rules()
    {
        return array(
        array('osrRequesterName,osrConsumerKey,osrConsumerSecret', 'required'),
        array('osrRequesterName', 'length', 'max'=>255),
        array('osrApplicationDescr', 'length', 'max'=>255),
        );
    }

    
    public function attributeLabels()
    {
        return array(
            'osrRequesterName'  => 'APP名称',
            'osrConsumerKey'    => 'APP KEY',
            'osrConsumerSecret' => 'APP SECRET',
            'osrApplicationDescr' => 'APP备注',
        );
    }
    
    
    private function _validateKeyAndSecret(){
        $app = ServerRegistry::model()->find("osr_consumer_key=? and osr_consumer_secret=?",array($this->osrConsumerKey, $this->osrConsumerSecret));
        if(isset($app)){
            $this->addError("osrConsumerKey", "已经存在相同的key或sevret");
            return false;
        }
        return true;
    }
    
    public function save(){

        if($this->validate()){
                        if($this->_validateKeyAndSecret()){
                                $user = Yii::app()->session["user"];
            	
                $app = new ServerRegistry();
                $app["osr_usa_id_ref"]=$user['id'];
                $app["osr_requester_name"]    =$this->osrRequesterName;
                $app["osr_consumer_key"]      =$this->osrConsumerKey;
                $app["osr_consumer_secret"]   =$this->osrConsumerSecret;
                $app["osr_application_descr"] =$this->osrApplicationDescr;
                $app["osr_enabled"]=1;
                $app["osr_status"]="active";
                
                $app["osr_issue_date"]=date('Y-m-d H:i:s',time());
                $app->save();
                return true;
            }
        }
        return false;
    }
}